package com.aizhixin.lab.project.course.service;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.core.UserInforCore;
import com.aizhixin.lab.project.course.entity.*;
import com.aizhixin.lab.project.course.repository.*;
import com.aizhixin.lab.project.template.core.WorkOrderFileType;
import com.aizhixin.lab.project.template.domain.DeleteDomain;
import com.aizhixin.lab.project.template.domain.ProjectRoleDomain;
import com.aizhixin.lab.project.template.domain.WorkOrderDomain;
import com.aizhixin.lab.project.template.domain.WorkOrderFileDomain;
import com.aizhixin.lab.project.template.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class TeacherTaskWorkOrderService {
    @Autowired
    private TeacherTaskWorkOrderRepository workOrderRepository;
    @Autowired
    private TeacherWorkOrderFileRepository workOrderFileRepository;
    @Autowired
    private TeacherModuleTaskRepository moduleTaskRepository;
    @Autowired
    private TeacherProjectRepository projectRepository;
    @Autowired
    private TeacherExercisesRepository teacherExercisesRepository;
    public void updateSort(List<String> ids){
        int i=1;
        for (String id : ids) {
            TeacherTaskWorkOrder taskWorkOrder = workOrderRepository.findOne(id);
            taskWorkOrder.setWorkOrderNo(i);
            workOrderRepository.save(taskWorkOrder);
            i++;
        }
    }
    /**
     * 老师端查看任务下的所有工单
     *
     * @param id
     * @return
     */
    public List<WorkOrderDomain> findWorkOrderByModuleId(String id) {
        List<TeacherTaskWorkOrder> workOrderList = workOrderRepository.findByTaskIdAndDeleteFlagOrderByWorkOrderNo(id, DataValidity.VALID.getState());
        List<WorkOrderDomain> workOrderDomainList = new ArrayList<>();
        for (TeacherTaskWorkOrder taskWorkOrder : workOrderList) {
            WorkOrderDomain workOrderDomain = new WorkOrderDomain();
            BeanUtils.copyProperties(taskWorkOrder, workOrderDomain);
            List<ProjectRoleDomain> roleDomainList = new ArrayList<>();
            for (ProjectRole projectRole : taskWorkOrder.getProjectRoleList()) {
                ProjectRoleDomain roleDomain = new ProjectRoleDomain();
                BeanUtils.copyProperties(projectRole, roleDomain);
                roleDomainList.add(roleDomain);
            }
            List list1 = new ArrayList();
            List list2 = new ArrayList();
            List list3 = new ArrayList();
            workOrderFileRepository.findByWorkOrderIdAndDeleteFlag(taskWorkOrder.getId(),DataValidity.VALID.getState()).stream().forEach(e->{
                WorkOrderFileDomain workOrderFileDomain = new WorkOrderFileDomain();
                BeanUtils.copyProperties(e,workOrderFileDomain);
                if (e.getFileType()==WorkOrderFileType.video.getIntValue()){
                    list1.add(workOrderFileDomain);
                }else if (e.getFileType()==WorkOrderFileType.material.getIntValue()){
                    list2.add(workOrderFileDomain);
                }else if (e.getFileType()==WorkOrderFileType.soundCode.getIntValue()){
                    list3.add(workOrderFileDomain);
                }

            });
            Integer count = teacherExercisesRepository.countByTaskId(workOrderDomain.getId());
            if (count>0){
                workOrderDomain.setIsExist(true);
            }else {
                workOrderDomain.setIsExist(false);
            }
            workOrderDomain.setVideo(list1);
            workOrderDomain.setSoundCode(list3);
            workOrderDomain.setWorkOrderMaterial(list2);
            workOrderDomain.setProjectRoleDomainList(roleDomainList);
            workOrderDomainList.add(workOrderDomain);
        }
        return workOrderDomainList;
    }

    /**
     * 老师端查看工单详情
     *
     * @param id
     * @return
     */
    public Map<String,Object> findWorkOrder(String id, AccountDTO dto) {
        Map<String,Object> result=new HashMap();
        TeacherTaskWorkOrder taskWorkOrder = workOrderRepository.findOne(id);
        if (Objects.isNull(taskWorkOrder)){
            result.put(ApiReturnConstants.SUCCESS,false);
            result.put(ApiReturnConstants.ERROR,"工单信息不存在");
            return result;
        }
        WorkOrderDomain workOrderDomain = new WorkOrderDomain();

        BeanUtils.copyProperties(taskWorkOrder, workOrderDomain);
        List<ProjectRoleDomain> roleDomainList = new ArrayList<>();
        List<TeacherWorkOrderFile> workOrderFileList = workOrderFileRepository.findByWorkOrderIdAndDeleteFlag(id, DataValidity.VALID.getState());
        if (dto.getRole().equals("student")){
            workOrderFileList=workOrderFileRepository.findByWorkOrderIdAndDeleteFlagAndIsHide(id,DataValidity.VALID.getState(),false);
        }else {
            workOrderFileList = workOrderFileRepository.findByWorkOrderIdAndDeleteFlag(id, DataValidity.VALID.getState());
        }
        List<WorkOrderFileDomain> video = new ArrayList<>();
        List<WorkOrderFileDomain> workOrderMaterial = new ArrayList<>();
        List<WorkOrderFileDomain> soundCode = new ArrayList<>();
        List<WorkOrderFileDomain> workStepList = new ArrayList<>();
        for (TeacherWorkOrderFile workOrderFile : workOrderFileList) {
            WorkOrderFileDomain domain = new WorkOrderFileDomain();
            BeanUtils.copyProperties(workOrderFile, domain);
            if (WorkOrderFileType.video.getIntValue().equals(domain.getFileType())) {
                video.add(domain);
            } else if (WorkOrderFileType.material.getIntValue().equals(domain.getFileType())) {
                workOrderMaterial.add(domain);
            } else if (WorkOrderFileType.soundCode.getIntValue().equals(domain.getFileType())){
                soundCode.add(domain);
            }else {
                workStepList.add(domain);
            }
        }
        for (ProjectRole projectRole : taskWorkOrder.getProjectRoleList()) {
            ProjectRoleDomain roleDomain = new ProjectRoleDomain();
            BeanUtils.copyProperties(projectRole, roleDomain);
            roleDomainList.add(roleDomain);
        }
        workOrderDomain.setWorkStepList(workStepList);
        workOrderDomain.setProjectRoleDomainList(roleDomainList);
        workOrderDomain.setSoundCode(soundCode);
        workOrderDomain.setWorkOrderMaterial(workOrderMaterial);
        workOrderDomain.setVideo(video);
        if (dto.getRole().equals(UserInforCore.ROLE_STUDENT)) {
            workOrderDomain.setSoundCode(null);
        }
        result.put(ApiReturnConstants.SUCCESS,true);
        result.put(ApiReturnConstants.DATA,workOrderDomain);
        return result;
    }

    /**
     * 保存工单
     *
     * @param domain
     * @return
     */
    public String save(WorkOrderDomain domain) {
        Boolean isNew = false;
        List<TeacherWorkOrderFile> workOrderFileList = new ArrayList<>();
        List<ProjectRole> projectRoles = new ArrayList<>();
        if (null == domain.getId() || "".equals(domain.getId())) {
            domain.setId(UUID.randomUUID().toString());
            isNew = true;
        }
        for (ProjectRoleDomain roleDomain : domain.getProjectRoleDomainList()) {
            ProjectRole projectRole = new ProjectRole();
            BeanUtils.copyProperties(roleDomain, projectRole);
            projectRoles.add(projectRole);
        }
        if (domain.getSoundCode() != null) {
            workOrderFileList.addAll(copyToWorkOrderFile(domain.getSoundCode(), WorkOrderFileType.soundCode.getIntValue(), domain.getId()));
        }
        if (domain.getWorkOrderMaterial() != null) {
            workOrderFileList.addAll(copyToWorkOrderFile(domain.getWorkOrderMaterial(), WorkOrderFileType.material.getIntValue(), domain.getId()));
        }
        if (domain.getVideo() != null) {
            workOrderFileList.addAll(copyToWorkOrderFile(domain.getVideo(), WorkOrderFileType.video.getIntValue(), domain.getId()));
        }
        if (domain.getWorkStepList() != null) {
            workOrderFileList.addAll(copyToWorkOrderFile(domain.getWorkStepList(), WorkOrderFileType.workStep.getIntValue(), domain.getId()));
        }
        if (isNew) {
            TeacherTaskWorkOrder taskWorkOrder = new TeacherTaskWorkOrder();
            BeanUtils.copyProperties(domain, taskWorkOrder);
            taskWorkOrder.setId(domain.getId());
            taskWorkOrder.setCreatedDate(new Date());
            taskWorkOrder.setDeleteFlag(DataValidity.VALID.getState());
            taskWorkOrder.setProjectRoleList(projectRoles);
            Integer workOrderNum = countWorkOrder(domain.getTaskId());
            taskWorkOrder.setWorkOrderNo(workOrderNum+1);
            TeacherModuleTask moduleTask = moduleTaskRepository.findOne(domain.getTaskId());
            if (!Objects.isNull(moduleTask)) {
                moduleTask.setWorkOrderNum(moduleTask.getWorkOrderNum() + 1);
                moduleTaskRepository.save(moduleTask);
            }
            TeacherProject project = projectRepository.findOne(domain.getProjectId());
            if (!Objects.isNull(project)) {
                project.setWorkOrderNum(project.getWorkOrderNum() == null ? 0 : project.getWorkOrderNum() + 1);
                projectRepository.save(project);
            }
            workOrderFileRepository.save(workOrderFileList);
            workOrderRepository.save(taskWorkOrder);
            return domain.getId();
        }

        TeacherTaskWorkOrder one = workOrderRepository.findOne(domain.getId());
        BeanUtils.copyProperties(domain, one);
        one.setProjectRoleList(projectRoles);
        workOrderFileRepository.deleteByWorkOrderId(one.getId());
        workOrderFileRepository.save(workOrderFileList);
        workOrderRepository.save(one);
        return domain.getId();
    }

    public List<TeacherWorkOrderFile> copyToWorkOrderFile(List<WorkOrderFileDomain> domains, Integer type, String taskWorkOrderId) {
        List<TeacherWorkOrderFile> workOrderFileList = new ArrayList<>();
        for (WorkOrderFileDomain fileDomain : domains) {
            TeacherWorkOrderFile workOrderFile = new TeacherWorkOrderFile();
            BeanUtils.copyProperties(fileDomain, workOrderFile);
            workOrderFile.setId(UUID.randomUUID().toString());
            workOrderFile.setWorkOrderId(taskWorkOrderId);
            workOrderFile.setFileType(type);
            workOrderFile.setDeleteFlag(DataValidity.VALID.getState());
            workOrderFileList.add(workOrderFile);
        }
        return workOrderFileList;
    }

    /**
     * 统计工单数
     *
     * @param taskId
     * @return
     */
    public Integer countWorkOrder(String taskId) {
        return workOrderRepository.countByTaskIdAndDeleteFlag(taskId, DataValidity.VALID.getState());
    }

    /**
     * 删除工单
     *
     * @param deleteDomain
     * @return
     */
    public Map<String, Object> delete(DeleteDomain deleteDomain) {
        Map<String, Object> result = new HashMap<String, Object>();
        TeacherTaskWorkOrder taskWorkOrder = workOrderRepository.findOne(deleteDomain.getId());

        if (Objects.isNull(taskWorkOrder)) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "未查询到工单");
        } else {
            TeacherProject project = projectRepository.findOne(deleteDomain.getProjectId());
            taskWorkOrder.setDeleteFlag(DataValidity.INVALID.getState());
            workOrderRepository.save(taskWorkOrder);
            if (!Objects.isNull(project)) {
                project.setWorkOrderNum(project.getWorkOrderNum()-1);
                projectRepository.save(project);
            }
            TeacherModuleTask moduleTask = moduleTaskRepository.findOne(taskWorkOrder.getTaskId());
            if (!Objects.isNull(moduleTask)) {
                moduleTask.setWorkOrderNum(countWorkOrder(taskWorkOrder.getTaskId()));
                moduleTaskRepository.save(moduleTask);
            }
            updateSort(taskWorkOrder.getTaskId());
            result.put(ApiReturnConstants.SUCCESS, true);
            result.put(ApiReturnConstants.DATA, "删除成功");
        }
        return result;
    }

    /**
     * 修改任务下的工单顺序
     *
     * @param taskId
     */
    public void updateSort(String taskId) {
        List<TeacherTaskWorkOrder> taskWorkOrderList = workOrderRepository.findByTaskIdAndDeleteFlagOrderByWorkOrderNo(taskId, DataValidity.VALID.getState());

        for (int i = 0; i < taskWorkOrderList.size(); i++) {
            taskWorkOrderList.get(i).setWorkOrderNo(i + 1);
        }
        workOrderRepository.save(taskWorkOrderList);
    }
}
